package com.xyauto.theme.utils

import android.app.Activity
import android.content.Context
import android.content.res.Resources
import android.text.TextUtils
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.TextView
import com.blankj.utilcode.util.LogUtils
import com.xyauto.theme.BuildConfig
import kotlin.math.abs
import kotlin.math.pow
import kotlin.math.sqrt

object AutoUtils {


    var displayWidth = 0
    var displayHeight = 0

    var designWidth = 0
    var designHeight = 0

    var textPixelsRate = 0.0
    var densityRate = 0.0


    /**
     * 初始化
     * @param act 上下文
     * @param hasStatusBar 是否计算状态栏
     * @param width  设计图宽度
     * @param height  设计图高度
     */
    fun init(context: Context, width: Int, height: Int, hasStatusBar: Boolean = false) {
        LogUtils.i("init: width=$width;height=$height")
        if (width < 1 || height < 1) return
        val dm = DisplayMetrics()
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        windowManager.defaultDisplay.getMetrics(dm)
        displayWidth = dm.widthPixels
        displayHeight = dm.heightPixels
        densityRate = (1 / dm.density).toDouble()

        if (hasStatusBar) {
            displayHeight -= getStatusBarHeight(context)
        }
        designWidth = width
        designHeight = height
        val displayDiagonal = sqrt(displayWidth.toDouble().pow(2.0) + displayHeight.toDouble().pow(2.0))
        val designDiagonal = sqrt(designWidth.toDouble().pow(2.0) + designHeight.toDouble().pow(2.0))
        textPixelsRate = displayDiagonal / designDiagonal
    }


    fun getStatusBarHeight(context: Context): Int {
        var result = 0
        try {
            val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
            if (resourceId > 0) {
                result = context.resources.getDimensionPixelSize(resourceId)
            }
        } catch (e: Resources.NotFoundException) {
            e.printStackTrace()
        }
        return result
    }


    fun auto(act: Activity) {
        if (displayWidth < 1 || displayHeight < 1) return
        auto(act.window.decorView)
    }

    private fun auto(it: ViewGroup) {
        for (i in 0 until it.childCount) {
            val child = it.getChildAt(i)
            if (child != null) {
                auto(child)
            }
        }
    }

    /**
     * 使View进行屏幕适配计算
     * @param view
     */
    fun auto(it: View) {
        if (displayWidth < 1 || displayHeight < 1) return
        autoTextSize(it)
        autoSize(it)
        autoPadding(it)
        autoMargin(it)
        if (it is ViewGroup) {
            auto(it)
        }
    }


    fun autoMargin(view: View) {
        view.layoutParams?.let {
            val lp = view.layoutParams as? ViewGroup.MarginLayoutParams ?: return
            lp.leftMargin = dw(lp.leftMargin)
            lp.topMargin = dh(lp.topMargin)
            lp.rightMargin = dw(lp.rightMargin)
            lp.bottomMargin = dh(lp.bottomMargin)
        }
    }


    fun autoPadding(view: View) {
        val l = dw(view.paddingLeft)
        val t = dh(view.paddingTop)
        val r = dw(view.paddingRight)
        val b = dh(view.paddingBottom)
        view.setPadding(l, t, r, b)
    }


    fun autoSize(view: View) {
        val lp = view.layoutParams ?: return
        var isSquare = false
        if (lp.width == lp.height) {
            isSquare = true
        }
        if (lp.width > 0) {
            lp.width = dw(lp.width)
        }
        if (lp.height > 0) {
            lp.height = dh(lp.height)
        }
        if (isSquare) {
            if (lp.width > lp.height) {
                lp.width = lp.height
            } else {
                lp.height = lp.width
            }
        }
    }


    fun autoTextSize(view: View) {
        if (view is TextView) {
            val designPixels = view.textSize.toDouble()
            val displayPixels = textPixelsRate * designPixels * densityRate
            view.includeFontPadding = false
            view.setTextSize(TypedValue.COMPLEX_UNIT_PX, displayPixels.toFloat())
        }
    }


    /**
     * 获取设计图宽度换算成当前分辨率的宽度
     * @param designWidthValue
     * @return
     */
    fun w(designWidthValue: Int): Int = if (abs(designWidthValue) < 2) designWidthValue else designWidthValue * displayWidth / designWidth

    fun dw(designWidthValue: Int): Int = if (abs(designWidthValue) < 2) designWidthValue else (designWidthValue * displayWidth / designWidth * densityRate).toInt()


    /**
     * 获取设计图高度换算成当前分辨率的高度
     * @param designHeightValue
     * @return
     */
    fun h(designHeightValue: Int): Int = if (abs(designHeightValue) < 2) designHeightValue else designHeightValue * displayHeight / designHeight


    fun dh(designHeightValue: Int): Int = if (abs(designHeightValue) < 2) designHeightValue else (designHeightValue * displayHeight / designHeight * densityRate).toInt()

    /**
     * 获取设计图字体大小换算成当前分辨率的字体大小
     * @param designTextSize
     * @return
     */
    fun getDisplayTextSize(designTextSize: Float): Float {
        return (textPixelsRate * designTextSize).toFloat()
    }

    fun getPreviewScale(): String {
//        val scale = BuildConfig.PREVIEW_SCALE
//        if (!TextUtils.isEmpty(scale) && scale.contains(":")) {
//            return scale
//        }
        return "$designWidth:$designHeight"
    }
}